<script lang="ts">

import {DepartmentVO, Permission, PositionVO, Result, UserVO} from "~/api/responseResult";
import {
  findDepartmentAll,
  findPositionAll,
  findUserAllByUserPid,
  findUserAllByUserQuery,
  getTablePermission, saveTablePermission
} from "~/api/warehouse";
import {arrayDeDuplication} from '~/utils'
import {QuestionFilled} from '@element-plus/icons-vue'
import {ElForm} from "element-plus";

interface PermissionState {
  tablePermission: Permission,
  administrators: Array<UserVO>,
  ordinaryUser: Array<UserVO>,
  departmentList: Array<DepartmentVO>,
  positionList: Array<PositionVO>,
  dialogVisible: boolean,
  tablePid: string,
  loading: boolean,
}

const initState: PermissionState = {
  tablePermission: {
    administrators: [],
    ordinaryUsers: [],
    departmentAndPosition: false,
    departments: [],
    positions: []
  },
  administrators: [],
  ordinaryUser: [],
  departmentList: [],
  positionList: [],
  dialogVisible: false,
  tablePid: '',
  loading: false,
}
export default defineComponent({
  name: 'SetPermission',
  components: {QuestionFilled},
  setup() {
    const cascadeProps = {
      multiple: true,
      checkStrictly: true,
      value: 'departmentCd',
      label: 'departmentName',
      children: 'departmentList',
      emitPath: false,

    }


    const state: PermissionState = reactive(initState)

    const rules = reactive({
      administrators: [
        {
          required: true,
          message: '请选择管理员',
          trigger: 'change',
        }
      ],
    })

    const loading = ref(false)
    const formRef = ref<InstanceType<typeof ElForm>>();

    const remoteMethod = async (query: string, identity: string) => {
      if (query) {
        loading.value = true
        let userQuery = {hrNo: query}
        const res: Result<Array<UserVO>> = await findUserAllByUserQuery(userQuery)
        if (res.success) {
          if (identity === 'administrator') {
            let list = res.data
            list.forEach(item => {
              if (state.tablePermission.ordinaryUsers.indexOf(item.userId) >= 0) {
                list = []
              }
            })
            let userList = state.administrators.concat(list)
            arrayDeDuplication(userList, 'userId')
            state.administrators = userList
          } else {
            let list = res.data
            list.forEach(item => {
              if (state.tablePermission.administrators.indexOf(item.userId) >= 0) {
                list = []
              }
            })
            let userList = state.ordinaryUser.concat(list)
            arrayDeDuplication(userList, 'userId')
            state.ordinaryUser = userList
          }
        }
        loading.value = false
      }
    }

    const getDepartmentAll = async () => {
      const res: Result<DepartmentVO> = await findDepartmentAll()
      if (res.success) {
        state.departmentList = [res.data]
      }
    }


    const getPositionAll = async () => {
      const res: Result<Array<PositionVO>> = await findPositionAll()
      if (res.success) {
        state.positionList = res.data
      }
    }


    const open = async (data: { tablePid: string }) => {
      state.tablePid = data.tablePid
      state.dialogVisible = true
      // 获取权限
      state.loading = true
      const res: Result<Permission> = await getTablePermission({tablePid: state.tablePid})
      if (res.success) {
        // 获取用户列表
        state.tablePermission = res.data
        if (state.tablePermission.administrators.length > 0) {
          const res1: Result<UserVO[]> = await findUserAllByUserPid(state.tablePermission.administrators);
          if (res1.success) {
            state.administrators = res1.data
          }
        }
        if (state.tablePermission.ordinaryUsers.length > 0) {
          const res2: Result<UserVO[]> = await findUserAllByUserPid(state.tablePermission.ordinaryUsers);
          if (res2.success) {
            state.ordinaryUser = res2.data
          }
        }
      }
      state.loading = false
    }

    const handleClose = () => {
      state.dialogVisible = false
      state.tablePermission = {
        administrators: [],
        ordinaryUsers: [],
        departmentAndPosition: false,
        departments: [],
        positions: []
      }
      state.administrators = []
      state.ordinaryUser = []
      state.tablePid = ''
    }

    const savePermission = async () => {
      const json: any = {};
      const permission: Permission = JSON.parse(JSON.stringify(state.tablePermission))
      json.tablePid = state.tablePid;
      json.administrators = permission.administrators.toLocaleString();
      json.ordinaryUsers = permission.ordinaryUsers.toLocaleString();
      json.positions = permission.positions.toLocaleString();
      json.departmentAndPosition = permission.departmentAndPosition.toLocaleString();
      json.departments = permission.departments.toLocaleString()
      const res: Result<any> = await saveTablePermission(json)
      if (res.success) {
        handleClose()
      }
    }

    const removeTag = (val: string, identity: string) => {
      if (identity === 'administrator') {
        let administrators = state.administrators
        for (let i = 0; i < administrators.length; i++) {
          if (administrators[i].userId === val) {
            // 移除
            administrators.splice(i, 1)
          }
        }
        state.administrators = administrators
      } else {
        let ordinaryUser = state.ordinaryUser
        for (let i = 0; i < ordinaryUser.length; i++) {
          if (ordinaryUser[i].userId === val) {
            // 移除
            ordinaryUser.splice(i, 1)
          }
        }
        state.ordinaryUser = ordinaryUser
      }

    }

    onBeforeMount(() => {
      getDepartmentAll()
      getPositionAll()
    })

    watch(() => state.tablePermission.departments, (newValue, oldValue) => {
      if (newValue.length === 0) {
        state.tablePermission.positions = []
      }
    })

    watch(() => state.tablePermission.departmentAndPosition, (newValue, oldValue) => {
      if (!newValue) {
        state.tablePermission.departments = []
        state.tablePermission.positions = []
      }
    })

    return {
      cascadeProps,
      state,
      loading,
      remoteMethod,
      formRef,
      rules,
      open,
      handleClose,
      savePermission,
      removeTag
    }
  }
})
</script>

<template>
  <el-dialog
      v-model="state.dialogVisible"
      title="设置权限"
      width="60%"
      :before-close="handleClose"
  >
    <div v-loading="state.loading">
      <el-form
          :rules="rules"
          ref="formRef"
          label-width="120px"
          class="demo-ruleForm"
          :model="state.tablePermission"
      >
        <el-form-item required label="管理员" prop="administrators">
          <el-select
              v-model="state.tablePermission.administrators"
              @remove-tag="(val) => removeTag(val, 'administrator')"
              style="width: 100%;"
              multiple
              filterable
              remote
              reserve-keyword
              :remote-method="(query: string) => remoteMethod(query, 'administrator')"
              :loading="loading"
              placeholder="管理员">
            <el-option
                v-for="userVO in state.administrators"
                :key="userVO.userId"
                :label="userVO.userLabel"
                :value="userVO.userId"/>
          </el-select>
        </el-form-item>


        <el-form-item label="普通用户">
          <el-select
              v-model="state.tablePermission.ordinaryUsers" style="width: 100%;"
              @remove-tag="(val) => removeTag(val, 'ordinaryUser')"
              multiple
              filterable
              remote
              reserve-keyword
              :remote-method="(query: string) => remoteMethod(query, 'ordinaryUser')"
              :loading="loading"
              placeholder="普通用户">
            <el-option
                v-for="userVO in state.ordinaryUser"
                :key="userVO.userId"
                :label="userVO.userLabel"
                :value="userVO.userId"/>
          </el-select>
        </el-form-item>

        <el-form-item label="指定部门/岗位（勾选后，选项为空时表示无限制）">
          <template #label>
            <span>指定部门/岗位</span>
            <el-icon>
              <QuestionFilled/>
            </el-icon>
          </template>
          <el-switch v-model="state.tablePermission.departmentAndPosition"></el-switch>
        </el-form-item>

        <el-form-item v-if="state.tablePermission.departmentAndPosition" label="部门">
          <el-cascader style="width: 100%;" v-model="state.tablePermission.departments" :options="state.departmentList"
                       :props="cascadeProps"
                       clearable/>
        </el-form-item>

        <el-form-item
            v-if="state.tablePermission.departmentAndPosition " label="且岗位">
          <el-select
              :disabled="state.tablePermission.departments.length == 0"
              v-model="state.tablePermission.positions" style="width: 100%;"
              multiple
              filterable
              placeholder="岗位">
            <el-option
                v-for="positionVO in state.positionList"
                :key="positionVO.positionId"
                :label="positionVO.positionName"
                :value="positionVO.positionId"/>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="savePermission">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>

</style>
